﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Dynamic;
using System.Linq;
using System.Text;

namespace UPNP.IO
{
    [System.Diagnostics.DebuggerStepThrough]
    public struct DynamicEnumerable
    {
        private readonly StringCollection _validValues;
        private string _value;

        public string Value
        {
            get
            {
                return _value;
            }

            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                if (_value != value)
                {
                    // check if valid
                    if (!_validValues.Contains(value))
                    {
                        throw new ArgumentOutOfRangeException("value", value, "enum value is not valid: " + value);
                    }

                    // everything is fine
                    _value = value;
                }
            }
        }

        public static bool operator == (DynamicEnumerable a, DynamicEnumerable b)
        {
            return (a._value == b._value);
        }

        public static bool operator != (DynamicEnumerable a, DynamicEnumerable b)
        {
            return (a._value != b._value);
        }

        public override bool Equals(object other)
        {
            if (other == null)
                return false;

            if (other is DynamicEnumerable)
            {
                // do not check if the valid values are
                // the same. only the value counts here
                return (_value == ((DynamicEnumerable)other)._value);
            }

            return false;
        }

        public override int GetHashCode()
        {
            // make sure we do not conflict
            // with string having that value
            return _value.GetHashCode() ^ 270646723;
        }

        public override string ToString()
        {
            return _value;
        }

        public DynamicEnumerable(IEnumerable<string> validValues)
        {
            if (validValues == null)
                throw new ArgumentNullException("validValues");

            // store valid values
            _validValues = new StringCollection();

            _validValues.AddRange(validValues.ToArray());

            if (_validValues.Count < 1)
                throw new ArgumentException("at least one value must be provided", "validValues");

            _value = _validValues[0];
        }
    }
}
